#/bin/sh
echo start build chong phoenix channel=$1,type=$2,branch=$3,repo=$4,apk_path=$5
. /usr/local/scripts/build_scripts/util.sh
source /etc/profile
unset DISPLAY #主要针对slave上反编译apk失败的情况
echo jenkins var as follow:
echo build_num=$BUILD_NUMBER
echo build_user_id=$BUILD_USER_ID
echo build_user=$BUILD_USER
echo job_name=$JOB_NAME
trigger_user=$BUILD_USER_ID
phoenix_channel=$1
phoenix_type=$2
ph_branch_tmp=$3
phoenix_repo=$4
ph_aapt="/usr/local/scripts/build_scripts/sign_apk_tool/aapt"
dir_name=$phoenix_channel
cur_path=`pwd`
#多个渠道时，使用逗号隔开，所以当包含逗号时，就认为输入的是多个渠道
if [ "$phoenix_repo" == "rec_app" -o "$phoenix_repo" == "send_app" -o "$phoenix_repo" == "rec_app_tob" ];then
    #单渠道构建或者多渠道构建
    if [ "$phoenix_channel" == "app_stores" ];then
       [ "$phoenix_repo" == "rec_app" ] && cp "/usr/local/scripts/build_scripts/all_channels" ./all_channels 
       [ "$phoenix_repo" == "send_app" ] &&  cp "/usr/local/scripts/build_scripts/mobile_assistant" ./all_channels 
        sed -i '/^\s*$/d' all_channels #删除空行
        channels_file="all_channels"
    else
        echo $phoenix_channel > app_channles
        if [ "x`echo "$phoenix_channel" |grep ","`" == "x" ];then #输入的渠道时候含有逗号，表示输入了多个渠道,否则，认为只输入了一个渠道
            echo just only input one channel=$phoenix_channel
        else
            echo user input one more channel=$phoenix_channel
            sed -i 's/,/\n/g' app_channles #逗号转换成换行符
            dir_name="more"
        fi
        echo app channels file as follow:
        cat app_channles
        channels_file="app_channles"
    fi

    #直接使用已经发布的apk来打渠道渠道的包，只需要填写ftp路径和渠道即可。
    if [ "x$5" != "x" ];then
        ftp_pwd=$5 #ftp服务的格式，比如ftp://192.168.8.251/output/phoenix_app/
        curl -u aolingli:ALL1234!  $ftp_pwd > ftp_info
        dapk_name=`cat ftp_info |grep .apk$ |awk -F " " '{print $4}'` #获取apk的名字
        echo apk path is $5 and apk_name=$dapk_name
        dmoulde_name=`echo $ftp_pwd  |awk -F "output/" '{print $2}' |awk -F "/" '{print $1}'` #获取包模块，是发送端app还是接收端app
        echo +++++++++++++++++++module=$dmoulde_name+++++++++++++++++++
        if [ "$dmoulde_name" == "phoenix_app" -a "$phoenix_repo" != "rec_app" ];then
            echo it is phoenix_app path but your repo is $phoenix_repo, path is wrong
            exit 1
        fi
        if [ "$dmoulde_name" == "phoenix_send_app" -a "$phoenix_repo" != "send_app" ];then
            echo it is phoenix_send_app but your repo is $phoenix_repo, path is wrong
            exit 1
        fi
        if [ "$dmoulde_name" == "phoenix_app_tob" -a "$phoenix_repo" != "rec_app_tob"  ];then
            echo it is phoenix_app path but your repo is $phoenix_repo, path is wrong
            exit 1
        fi
        mkdir download_target
        curl -u aolingli:ALL1234! -o download_target/$dapk_name  $ftp_pwd$dapk_name #下载ftp上的apk
        echo package info as follow:
        $ph_aapt dump badging download_target/$dapk_name  |grep package #显示apk的包名
        [ "$phoenix_repo" == "rec_app" ] && tmp_fd=phoenix_app
        [ "$phoenix_repo" == "send_app" ] && tmp_fd=phoenix_send_app
        [ "$phoenix_repo" == "rec_app_tob" ] && tmp_fd=phoenix_app_tob
        for  my_ch in `cat $channels_file`
            do
            {
                echo  +++++++++++++++++++++++++++++++++++$my_ch packaging ++++++++++++++++++++++++++++++++++++++
                mkdir target
                cp download_target/$dapk_name target/
                if [ "$phoenix_repo" == "rec_app" -o "$phoenix_repo" == "rec_app_tob" ];then
                    phoenix_app_special_channels $dapk_name $my_ch  #特殊渠道处理
                    replace_channel_conf $dapk_name $my_ch rec_app_info.conf $phoenix_repo #追压appid，secret
                else
                    replace_channel_conf $dapk_name $my_ch send_app_info.conf  $phoenix_repo  #发送端目前没有特殊处理的渠道，所以单纯追加即可
                fi
                dapk_name_up=`echo $dapk_name |sed s/happytest/$my_ch/g`
                echo upload file $dapk_name_up
                rm target/hpplay-happytest* -rf
                echo target file: `ls target/`
                curl -u aolingli:ALL1234! -T target/"$dapk_name_up" ftp://192.168.8.251/output/$tmp_fd/public_channels/  #上传处理好的apk到ftp上
                rm target -rf
            }
        done
        echo ftp_path="ftp://192.168.8.251/output/$tmp_fd/public_channels/"
        exit 0
    fi
fi

[ "x$BUILD_USER_ID" == "x" ] && trigger_user=$BUILD_USER
[ "x$BUILD_USER" == "x" ] && trigger_user=Timer
echo user $trigger_user trigger this build

#app中如果有tag,则使用tag,忽略分支名
[ "$phoenix_repo" == "rec_app" -o "$phoenix_repo" == "send_app" -o "$phoenix_repo" == "rec_app_tob" ] && repo_tag=`cat build_tags |grep apk_tag |awk -F "=" '{print $2}'`
#sdk中如果有tag,则使用tag,忽略分支名
[ "$phoenix_repo" == "rec_sdk" -o "$phoenix_repo" == "send_sdk" ] && repo_tag=`cat build_tags |grep sdk_tag |awk -F "=" '{print $2}'`


if [ "x$repo_tag" != "x" ];then
    echo repo_tag=$repo_tag
    check_tag $repo_tag
    git checkout $repo_tag
    ph_branch_tmp=$repo_tag
else
    git checkout $3
    git pull
fi

now_time=`date "+%Y%m%d%H%M"`
commit=`git rev-parse --short HEAD`
ph_branch=`echo $ph_branch_tmp |sed 's/\.//g'` #删除分支名中的点符号
 
if [ "x$1" == "x" -a "x$2" == "x" ];then
    now_time="$now_time"_"$ph_branch"_"$commit"_"$trigger_user"
else
    now_time="$now_time"_"$ph_branch"_"$commit"_"$trigger_user"_"$dir_name"_"$phoenix_type"
fi

old_channel=$phoenix_channel
[ -f gradlew ] && chmod 777 gradlew
if [ "$phoenix_repo" == "rec_sdk" ] ; then
    cp /usr/local/scripts/build_scripts/local.properties android/sink/
    ph_ftp_dir=phoenix_sdk
fi
[ "$phoenix_repo" == "send_sdk" ]  &&  ph_ftp_dir=phoenix_send_sdk

#接发端app代码以默认渠道happytest打包后，再（签名和）追压其他渠道的appid和secret信息，
#然后修改名字为所需渠道的名字，所以设置构建渠道为空
if [ "$phoenix_repo" == "rec_app" -o "$phoenix_repo" == "rec_app_tob" ] ; then
    cp /usr/local/scripts/build_scripts/local.properties ./
    phoenix_channel=" "
fi
[ "$phoenix_repo" == "rec_app" ] &&  ph_ftp_dir=phoenix_app
[ "$phoenix_repo" == "rec_app_tob" ] &&  ph_ftp_dir=phoenix_app_tob
[ "$phoenix_repo" == "send_app" ] &&  ph_ftp_dir=phoenix_send_app &&  phoenix_channel=" "

chmod 777 build.sh
#先构建sdk
if [ "$phoenix_repo" == "rec_app" -o "$phoenix_repo" == "rec_app_tob" ] ; then
    echo start build SDK:leboapk.....
    phoenix_build_leboapk "$ph_ftp_dir"/$now_time $phoenix_type  recsdk
fi

if [ "$phoenix_repo" == "rec_app" ] ; then
    #接受端app需要修改包名的渠道：leupgrade,jianguo_up,dangbei_ty,hisense_inner
    if [ "$old_channel" == "leupgrade" -o "$old_channel" == "jianguo_up" -o "$old_channel" == "dangbei_ty" -o "$old_channel" == "hisense_inner" ];then 
        echo $old_channel need to change package name
        sed -i s/"com.hpplay.happyplay.aw"/"com.hpplay.happyplay.aw.new"/g app/build.gradle
        git diff app/build.gradle
        pkg_flag=`grep -r "\"com.hpplay.happyplay.aw.new"\" app/build.gradle`
        echo pkg_flag=$pkg_flag
        if [ "x$pkg_flag" != "x" ];then #检查是否修改正确
            echo modify pkg name success
        else
            echo modify fail and exit
            exit 1
        fi
    fi
    #GIMI的这个改动是临时的，需要的时候再把注释去掉即可
    #改动:GIMI的包需要添加android:sharedUserId=“android.uid.system”
    #[ "$old_channel" == "GIMI" ] && rec_app_gimi
fi
if [ "$phoenix_repo" == "send_app" ] ; then
    echo start build SDK:leboapk.....
    phoenix_build_leboapk  "$ph_ftp_dir"/$now_time $phoenix_type sendsdk #发送端app也首先构建sdk
fi
echo cur path=`pwd`
git status
git diff
echo "build_channle=$phoenix_channel"
if [ "$phoenix_repo" == "rec_sdk" ] ; then #接收端sdk参数处理并打包
    sed -i 's/,/\n/g' sdk_config
    echo sdk config as follow:
    cat sdk_config
    echo sdk config as follow: > sdk_info
    cat sdk_config >> sdk_info
    echo >> sdk_info
    echo commitid:`git rev-parse HEAD` >> sdk_info
    have_ijk=`cat sdk_config |grep have_ijk |awk -F "=" '{print $2}'`
    have_custom=`cat sdk_config |grep have_custom |awk -F "=" '{print $2}'`
    have_free=`cat sdk_config |grep have_free |awk -F "=" '{print $2}'`
    player_ui=`cat sdk_config |grep player_ui |awk -F "=" '{print $2}'`
    have_domain=`cat sdk_config |grep have_domain |awk -F "=" '{print $2}'`
    #:<<! #多行注释
    #!
    sdk_fit_tag=${ph_branch_tmp:0:14} #截取tag字符串的14位,类似表示所有tag_r60008_1830*的tag
    sdk_fit_branch=${ph_branch_tmp:0:6} #截取tag字符串的6位,类似表示所有r6000*的分支 
    echo sdk_fit_tag=$sdk_fit_tag and sdk_fit_branch=$sdk_fit_branch
    if [ "$ph_branch_tmp" == "r60008_183_bugfix_2.0" -o "$sdk_fit_tag" == "tag_r60008_183" -o "$sdk_fit_tag" == "tag_r60010_185" \
        -o "$sdk_fit_branch" == "r60010" -o "$sdk_fit_branch" == "r60009" ]; then
        # 参数需要为key value 形式，可参考如下 base 目录下的 build.sh
        #channel:leboapk,buildtype:release,demoName:demo,onlybuild:0,ijk:1,free:1,playerUI:1,bangcleFile:1,domain:0
        # channel:     渠道，默认是happytest
        # buildtype:   release or debug，默认是debug
        # demoName:    demo名称，demo,demo-raw,demo-player,demo-jar,demo-ding,demo-option 默认是demo
        # onlybuild:   1 build&install ; 0 build only，默认是1
        # ijk:         是否需要ijk 1需要，0不需要，2不需要liblbffmpeg.so(满足sdk包尽量小的需求) 默认1
        # free:        是否是免费版本sdk    1 免费，0不免费。默认1
        # playerUI:    是否使用乐播播放UI   1 是，0否。默认1
        # bangcleFile: 加固策略   0都不加固，1加固so及aar， 2仅加固so， 3仅加固aar，默认2
        # domain:      域名配置   0乐播域名，1 CIBN域名   默认0
        # dlna: dlna开关生效值配置，1表示默认的dlna开关生效值配置（0(关)/1(开)），2 表示修改dlna生效开关值（8888(关)/9999(开)）
       build_var="channel:$phoenix_channel,buildtype:$phoenix_type,demoName:$have_custom,onlybuild:0,ijk:$have_ijk,free:$have_free,playerUI:$player_ui,domain:$have_domain"
        echo develop branch build_var=$build_var 
        echo command:sh build.sh $build_var >> sdk_info
        sh build.sh $build_var |tee build_result
        # echo "config:$phoenix_channel $phoenix_type $have_custom 0 $have_ijk $have_free $player_ui "  
        # sh build.sh $phoenix_channel $phoenix_type $have_custom 0 $have_ijk $have_free $player_ui |tee build_result
    else 
        # $1: 渠道，默认是happytest
        # $2: release or debug，默认是debug
        # $3: demo名称，demo,demo-raw,demo-player,demo-jar,demo-ding,默认是demo
        # $4: 1 build&install ; 0 build only，默认是1
        # $5: 是否需要ijk 1需要，0不需要，2不需要liblbffmpeg.so(满足sdk包尽量小的需求) 默认1
        # $6: 是否是免费版本sdk    1 免费，0不免费。默认1
        # $7: 是否使用乐播播放UI   1 是，0否。默认1
        # $8: 文件加固策略   0都不加固， 1加固so及aar， 2仅加固so， 3仅加固aar，默认1
        echo "sh build.sh $phoenix_channel $phoenix_type $have_custom 0 $have_ijk $have_free $player_ui "  
        echo "command:sh build.sh $phoenix_channel $phoenix_type $have_custom 0 $have_ijk $have_free $player_ui " >> sdk_info 
        sh build.sh $phoenix_channel $phoenix_type $have_custom 0 $have_ijk $have_free $player_ui  |tee build_result
    fi 
else
    if [ "$phoenix_repo" == "send_sdk" ];then
        echo this is sender sdk building .....
        echo this is sender sdk building .....
        sed -i 's/,/\n/g' send_sdk_conf
        echo send sdk config as follow:
        cat send_sdk_conf
        echo send sdk config as follow: > sdk_info
        cat send_sdk_conf >> sdk_info
        echo >> sdk_info
        demo_name=`cat send_sdk_conf |grep demo_name |awk -F "=" '{print $2}'`
        upload_maven=`cat send_sdk_conf |grep upload_maven |awk -F "=" '{print $2}'`
        have_mirror=`cat send_sdk_conf |grep have_mirror |awk -F "=" '{print $2}'`
        option_mirror=`cat send_sdk_conf |grep option_mirror |awk -F "=" '{print $2}'`
        is_conference=`cat send_sdk_conf |grep is_conference |awk -F "=" '{print $2}'`
        simple_tag_flag=0
        simple_branch_flag=0
        if [ "x$repo_tag" != "x" ];then #tag_r31601后的tag
            echo tag:$repo_tag >> sdk_info
            simple_tag=`echo ${repo_tag:5:10}` #取字符串的第五个到第十个字符(顺序从0开始)
            echo repo_tag=$repo_tag and simple_tag=$simple_tag
            [ $simple_tag -gt 31601 ] && simple_tag_flag=1
        else #r31600_bugfix_1.0后的分支
            echo branch:$3 >> sdk_info
            send_fb=$3
            simple_branch=`echo ${send_fb:1:5}` #取字符串的第一个到第五个字符（顺序从0开始）
            echo send_fb=$send_fb and simple_branch=$simple_branch
            [ $simple_branch -gt 31600 ] && simple_branch_flag=1
        fi
        echo commitid:`git rev-parse HEAD` >> sdk_info
        echo  >> sdk_info
        echo build shell command as follow: >> sdk_info
        echo simple_tag_flag=$simple_tag_flag and simple_branch_flag=$simple_branch_flag
        #r31600_bugfix_1.0以后的分支和tag_r31601以后的tag和develop分支:都使用新的构建脚本
        if [ "$simple_tag_flag" == "1" -o "$simple_branch_flag" == "1" -o "$3" == "develop" -o "$3" == "master" ]; then
            ## 参数
            # $1: 渠道：默认是happytest
            # $2: 编译类型：release or debug，默认是debug
            # $3: 安装类型：0 build only,1 build&install ; 默认是1
            # $4: option: 0 公版选项，1 去除镜像 ，2 只保留镜像，3 只保留镜像，去除common和gson包,默认值0
            # $5: demoName: demo名称，demo,demo-mirror,demo-conference-source 默认是demo
            # $6: uploadMaven: 0 不上传，1需要上传到maven,默认值0
            # $7: isConference: 0 普通版，1会议室版本，默认值为0
            echo "sh build.sh $phoenix_channel $phoenix_type 0 $option_mirror $demo_name $upload_maven $is_conference"
            echo "sh build.sh $phoenix_channel $phoenix_type 0 $option_mirror $demo_name $upload_maven $is_conference" >>sdk_info
            sh build.sh $phoenix_channel $phoenix_type 0 $option_mirror $demo_name $upload_maven $is_conference |tee build_result
        else
            if [ "$repo_tag" == "tag_r31551"  -o "$repo_tag" == "tag_r31552" ];then #这两个tag是在AndroidSendSDKForToB,打包脚本不一样
                echo "sh build-mirror-apk.sh $phoenix_channel $phoenix_type 0 0 "
                echo "sh build-mirror-apk.sh $phoenix_channel $phoenix_type 0 0 " >> sdk_info
                sh build-mirror-apk.sh $phoenix_channel $phoenix_type 0 0 |tee build_result
            else #老分支发送端sdk打包
                ## 参数
                # $1: 渠道：默认是happytest
                # $2: 编译类型：release or debug，默认是debug
                # $3: 安装类型：0 build only,1 build&install ; 默认是1
                # $4: 是否使用镜像：0不需要,1 需要;默认1
                echo "sh build.sh $phoenix_channel $phoenix_type 0 $have_mirror"
                echo "sh build.sh $phoenix_channel $phoenix_type 0 $have_mirror" >> sdk_info
                sh build.sh $phoenix_channel $phoenix_type 0 $have_mirror |tee build_result
            fi
        fi
    else
        echo this is other repos building .....
        echo "sh build.sh $phoenix_channel $phoenix_type "
        sh build.sh $phoenix_channel $phoenix_type |tee build_result #其他端打包
    fi
fi

get_build_result #判断是否打包成功

if [ "$phoenix_repo" == "rec_app" -o "$phoenix_repo" == "send_app" -o "$phoenix_repo" == "rec_app_tob" ] ; then
    if [ "$phoenix_repo" == "rec_app" -o "$phoenix_repo" == "rec_app_tob" ] ; then #接收端app回收处理
        mv sdk_info target/
        [ -d "app/build/outputs/mapping/$1/release" ] && cp app/build/outputs/mapping/$1/release/* target/
        [ -d "app/build/outputs/mapping/release" ] && cp app/build/outputs/mapping/release/* target/
    fi
    [ "$phoenix_repo" == "send_app" ]  && mv sdk_info target/ #发送端app只回收sdk_info

    mkdir bak_target
    mv target/*.apk bak_target/
    echo bak_target as follow:
    ls bak_target/
    echo package info as follow: #显示包名信息（主要关注有修改包名的渠道）
    [ "$phoenix_type" == "debug" -o "$phoenix_type" == "release" ] &&  $ph_aapt dump badging bak_target/"hpplay-happytest-$phoenix_type"*.apk  |grep package
    [ "$phoenix_type" == "all" ] &&  $ph_aapt dump badging bak_target/"hpplay-happytest-release"*.apk  |grep package
    for new_channel in `cat $channels_file` #渠道处理
        do
            echo ======================start deal with $new_channel======================
            [ "$phoenix_type" == "debug" -o "$phoenix_type" == "release" ] &&  deal_with_phoenix $phoenix_type $new_channel $phoenix_repo
            if [ "$phoenix_type" == "all" ];then
                deal_with_phoenix "release" $new_channel $phoenix_repo
                deal_with_phoenix "debug" $new_channel $phoenix_repo
            fi
    done
fi

[ "$phoenix_repo" == "rec_sdk" -a "$phoenix_type" == "release" ]  &&  cp android/sink/sdk-api/libs target/ -rn  #release的接收端sdk要回收libs

if [ "$phoenix_repo" == "rec_sdk" -o "$phoenix_repo" == "send_sdk" ] ; then #sdk回收处理
    sdk_path=`pwd`
    echo sdk now path=$sdk_path
    mv sdk_info target/
    cp target target_all -rn
    mv target target_tmp
    mkdir target
    #接收端sdk如果demo不是demo-option,需要把demo apk放到public中，否则放在public外面（因为demo-option 是对内的，不能给外面）
    [ "$phoenix_repo" == "rec_sdk" ]  &&  mv  target_tmp/*.tar  target_tmp/*.aar  target_tmp/*.jar  target/
    [ "$phoenix_repo" == "rec_sdk" -a "$have_custom" != "demo-option" ]  &&  mv target_tmp/*.apk  target/
    if [ "$phoenix_repo" == "send_sdk" ] ; then
        mv target_tmp/public/*  target/
        rm target_tmp/public -rf
    fi
    upload_file $ph_ftp_dir/$now_time/ public
    cd $sdk_path
    rm target -rf
    mv target_tmp target
fi

upload_file $ph_ftp_dir/ $now_time  #上传文件到ftp
send_email $JOB_NAME  $trigger_user #发送邮件
